#include "UdpHandler.h"
#include <QHostAddress>
#include <QByteArray>
#include <QString>
#include <QVariant>

UdpHandler::UdpHandler(QObject *parent)
    : QObject(parent)
{
    socket = new QUdpSocket(this);

    // 设置接收缓冲区大小（单位：字节）
    socket->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption, 65536); // 64 KB
    // 设置发送缓冲区大小（单位：字节）
    socket->setSocketOption(QAbstractSocket::SendBufferSizeSocketOption, 65536); // 64 KB

    // 监听UDP数据到达信号
    connect(socket, &QUdpSocket::readyRead, this, &UdpHandler::readData);
}

UdpHandler::~UdpHandler()
{
    delete socket;
}

void UdpHandler::startListening(QHostAddress &address, quint16 port)
{
    if (!socket->bind(address, port)) {
        qDebug() << socket->errorString();
    }
}

void UdpHandler::startListen()
{
    if (!socket->bind(this->address, this->port)) {
        qDebug() << socket->errorString();
    }
}

void UdpHandler::stopListening()
{
    socket->close();
}

void UdpHandler::readData()
{
    while (socket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);


        FlightData flightData = sigprocess->parseFlightData(datagram);
        emit dataReceived(flightData, sender, senderPort);
    }
}
